<template>
  <div class="orders-container" ref="orders" style="opacity: 0.88;">
    <h2>我的订单</h2>
  <el-menu :default-active="activeStatus" mode="horizontal" @select="filterOrders">
      <el-menu-item index="all">所有订单</el-menu-item>
      <el-menu-item index="unpaid">未支付</el-menu-item>
      <el-menu-item index="paid">已支付</el-menu-item>
      <el-menu-item index="completed">已完成</el-menu-item>
      <el-menu-item index="refund">申请退款中</el-menu-item>
      <el-menu-item index="refundsuccess">退款成功</el-menu-item>
    </el-menu>
    <div v-if="filteredOrders && filteredOrders.length">
      <div v-for="order in filteredOrders" :key="order.id" class="order">
        <p>订单号: {{ order.id }}</p>
        <div class="products">
          <div v-for="product in order.products" :key="product.id" class="product">
            <img :src="product.image" alt="Product Image" class="product-image">
            <div class="product-details">
              <p class="product-name">{{ product.name }}</p>
              <p class="product-price">价格: ¥{{ product.price }}</p>
              <p class="product-quantity">购买数量: {{ product.orderQuantity }}</p>
            </div>
          </div>
        </div>
        <div class="order-summary">
          <p>总金额: ¥{{ order.totalAmount }}</p>
          <p>状态: {{ order.status }}</p>
          <el-button v-if="order.status === '未支付'" type="warning" @click="toSuccessBuy(order.id)">前往支付</el-button>
          <el-button v-if="order.status === '已支付'" type="danger" @click="openRefundDialog(order.id)">取消订单</el-button>
          <el-button v-if="order.status === '已支付'" type="success" @click="confirmreceipt(order.id)">确认收货</el-button>
          <el-button v-if="order.status === '已完成'" type="warning" @click="openRefundDialog(order.id)">申请退款</el-button>
        </div>
      </div>
    </div>
    <div v-else>
      <p>还没有订单。</p>
    </div>

    <el-dialog v-model="refundDialogVisible" title="填写退款原因" width="50%">
      <el-input v-model="refundReason" type="textarea" placeholder="请输入退款原因"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRefund">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      orders: [],
      filteredOrders: [],
      refundDialogVisible: false,
      refundReason: '',
      currentOrderId: null,
      activeStatus: 'all',
    }
  },
  created() {
    this.fetchOrders();
  },
  methods: {
    toSuccessBuy(orderId) {
      this.$router.push({ 
        path: '/successBuy',
        query: { orderId: Number(orderId) }
      });
    },
    fetchOrders() {
      axios.get('http://localhost:8080/api/orders')
        .then(response => {
          const allOrders = response.data;
          const username = this.$globalState.username;
          this.orders = allOrders.filter(order => order.username === username);
          this.orders.forEach(order => order.products = order.products || []);
          this.filteredOrders = this.orders;
          this.filterOrders('all');
        })
        .catch(error => {
          console.error("There was an error fetching the orders!", error);
          if (error.response) {
            console.error("Server responded with status:", error.response.status);
            console.error("Response data:", error.response.data);
          } else {
            console.error("Error message:", error.message);
          }
        });
    },

    filterOrders(status) {
      this.activeStatus = status;
      if (status === 'all') {
        this.filteredOrders = this.orders;
      } else if (status === 'unpaid') {
        this.filteredOrders = this.orders.filter(order => order.status === '未支付');
      } else if (status === 'paid') {
        this.filteredOrders = this.orders.filter(order => order.status === '已支付');
      } else if (status === 'completed') {
        this.filteredOrders = this.orders.filter(order => order.status === '已完成');
      }else if (status === 'refund') {
        this.filteredOrders = this.orders.filter(order => order.status === '申请退款中');
      }else if (status === 'refundsuccess') {
        this.filteredOrders = this.orders.filter(order => order.status === '退款成功');
      }
    },

    openRefundDialog(orderId) {
      this.currentOrderId = orderId;
      this.refundDialogVisible = true;
    },

    confirmreceipt(orderId){
      // orderId = Number(this.orderId); 
      axios.post('http://localhost:8080/api/orders/updateStatus', { orderId: orderId, status: '已完成' });
      this.fetchOrders();
      
    },

    submitRefund() {
      if (!this.refundReason) {
        ElMessage.error('请填写退款原因');
        return;
      }

      axios.post(`http://localhost:8080/api/orders/${this.currentOrderId}/refund`, { reason: this.refundReason })
        .then(response => {
          ElMessage.success('退款申请已提交');
          this.refundDialogVisible = false;
          this.refundReason = '';

          // 刷新订单列表
          this.fetchOrders();
        })
        .catch(error => {
          ElMessage.error('提交退款申请时出错');
          console.error("There was an error submitting the refund request!", error);
        });
    }
  }
}
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f0f4f7;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  font-size: 2em;
    text-align: center;
    text-shadow: 5px 5px 5px #0e42ff;
    margin-bottom: 20px;
}

.el-menu {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.order {
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.products {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.product {
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  width: calc(50% - 20px);
  background-color: #fafafa;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 20px;
  border-radius: 10px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
}

.product-price,
.product-quantity {
  font-size: 14px;
  color: #555;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.order-summary p {
  margin: 5px 0;
}

.el-button {
  margin-top: 10px;
}
</style>